<template>
  <el-col :span="config.span">
    <div
      ref="container"
      class="form-item-container"
    >
      <form-item-layout
        v-if="isVisible"
        :current-item="currentItem"
        @change="$emit('change', $event)"
        @active-item="handleActiveItem"
        @change-label="$emit('change-label', $event)"
        @copy-item="$emit('copy-item', $event)"
        @delete-item="$emit('delete-item', $event)"
        @add-bank="$emit('add-bank', $event)"
      />
      <div
        v-else
        class="lazy-placeholder"
      >
        <el-skeleton :rows="2" />
      </div>
    </div>
  </el-col>
</template>

<script lang="ts" setup>
import { computed, defineAsyncComponent, nextTick, onMounted, onUnmounted, ref } from "vue";
import { ElSkeleton } from "element-plus";

const props = defineProps({
  currentItem: Object,
  scrollContainer: {
    type: String,
    default: ""
  }
});

const config = computed<any>(() => props.currentItem?.config);

const FormItemLayout = defineAsyncComponent(() => import("./FormItemLayout.vue"));

const container = ref<HTMLElement | null>(null);
const isVisible = ref(false);
let observer: IntersectionObserver | null = null;

onMounted(async () => {
  // 确保DOM已经更新
  await nextTick();

  // 获取滚动容器，el-scrollbar的实际滚动元素是.el-scrollbar__wrap
  const rootElement = props.scrollContainer ? document.querySelector(`${props.scrollContainer} .el-scrollbar__wrap`) : null;

  // 确保container.value是一个有效的DOM元素
  if (!container.value || !(container.value instanceof Element)) {
    console.warn("Container is not a valid DOM element");
    isVisible.value = true;
    return;
  }

  try {
    observer = new IntersectionObserver(
      entries => {
        const entry = entries[0];
        if (entry.isIntersecting) {
          isVisible.value = true;
          // 一旦组件可见就不再需要观察
          observer?.disconnect();
        }
      },
      {
        root: rootElement,
        threshold: 0.1, // 当10%的内容可见时触发
        rootMargin: "100px 0px" // 提前100px开始加载，提供更好的用户体验
      }
    );

    // 确保在观察之前元素已经挂载到DOM中
    if (container.value.isConnected) {
      observer.observe(container.value);
    } else {
      console.warn("Container is not connected to DOM");
      isVisible.value = true;
    }
  } catch (error) {
    console.error("Error setting up IntersectionObserver:", error);
    // 如果观察器设置失败，默认显示内容
    isVisible.value = true;
  }
});

onUnmounted(() => {
  observer?.disconnect();
});

const emit = defineEmits(["active-item", "change", "change-label", "copy-item", "delete-item", "add-bank"]);

const handleActiveItem = (child: any, currentItem: any) => {
  emit("active-item", child, currentItem);
};
</script>

<style scoped>
.form-item-container {
  width: 100%;
}

.lazy-placeholder {
  padding: 20px;
  border: 1px dashed #dcdfe6;
  border-radius: 4px;
  margin-bottom: 10px;
}
</style>
